How do you write a log file in a thread-safe way?
How do you write a log file in a thread-safe way?
Ravi Vishwakarma is a dedicated Software Developer with a passion for crafting efficient and innovative solutions. With a keen eye for detail and years of experience, he excels in developing robust software systems that meet client needs. His expertise spans across multiple programming languages and technologies, making him a valuable asset in any software development project.
ICSM Computer
30-May-2025To write a log file in a thread-safe way in C#, you need to ensure that multiple threads don't write to the file simultaneously, which can cause corruption or data loss.
Recommended Approach: Use
lockfor Thread SafetyExample: Basic Thread-Safe Logger
Usage:
lockensures only one thread writes at a time.AppendAllTextis used to append without overwriting the file.Alternative: Use
StreamWriterwithlockIf you're doing frequent logging, reusing a
StreamWriteris more efficient:Usage:
Dispose when done (or use with a
usingblock).High-Performance Option: Use
ConcurrentQueue+ Background WriterFor high throughput or async apps, log to a queue and let a background thread write to the file.
Let me know if you'd like a full example of that pattern.
Summary
lock+File.AppendAllTextlock+ sharedStreamWriterConcurrentQueue+ worker thread